package com.rbac.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbac.common.uils.R;
import com.rbac.entity.User;
import com.rbac.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author JianBinHuang
 * @Date 2021/9/24 11:24
 * @Description
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * @param
     * @return
     * @Author JianBinHuang
     * @Date 2021/9/24 17:13
     * @Description 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody User user) {
        return R.out(userService.save(user));
    }

    /**
     * @param
     * @return
     * @Author JianBinHuang
     * @Date 2021/9/24 17:44
     * @Description 分页
     * 前端的请求也必须是post 带可以携带requestBody
     * 请求到前端，不然只是getmapping 会请求不到
     */
    @PostMapping("/page")
    public R getPageList(@RequestBody Page<User> page) {
        page = userService.page(page);
        return R.putData("page", page);
    }

    /**
     * @param
     * @return
     * @Author JianBinHuang
     * @Date 2021/9/24 17:47
     * @Description 删除
     */
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable Integer id) {
        return R.out(userService.removeById(id));
    }

    /**
     * @param
     * @return
     * @Author JianBinHuang
     * @Date 2021/9/24 17:47
     * @Description 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody User user) {
        return R.out(userService.updateById(user));
    }

    /**
     * @param
     * @return
     * @Author JianBinHuang
     * @Date 2021/9/24 17:48
     * @Description 查询单个
     */
    @GetMapping("/getById/{id}")
    public R getById(@PathVariable Integer id) {
        User byId = userService.getById(id);
        return R.putData("data", byId);
    }


    /**
     * @param
     * @return
     * @Author JianBinHuang
     * @Date 2021/9/28 11:49
     * @Description
     *
     * 这里使用Map接收前端发过来的请求
     * 这样的接收方式比较好，
     * 因为如果是使用String接收的话会出现
     * {"username"="11111"}
     * 会被当做对象传过来
     */
    @PostMapping("/list")
    public R list(@RequestBody Map<String,Object> map) {

        QueryWrapper queryWrapper=new QueryWrapper();
        Object username = map.get("username");
        if(username!=null&&!ObjectUtils.isEmpty(username)){
            queryWrapper.like("username", username);
        }
        return R.putData("data", userService.list(queryWrapper));
    }
}
